<template>
  <view class="file-detail-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="文件详情" 
      :border="false"
      left-icon="arrow-left"
      @leftClick="goBack"
      :background="{ background: 'linear-gradient(135deg, #4a6bef, #7a5af8)' }"
      :titleStyle="{ color: '#ffffff', fontSize: '34rpx', fontWeight: 'bold' }"
      :leftIconColor="'#ffffff'"
    >
      <template #right>
        <view class="navbar-right" @tap="showActions = true">
          <u-icon name="more-dot-fill" size="20" color="#ffffff"></u-icon>
        </view>
      </template>
    </u-navbar>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="flower" size="36" color="#4a6bef"></u-loading-icon>
      <text class="loading-text">正在加载文件信息...</text>
    </view>
    
    <!-- 文件信息 -->
    <view v-else-if="fileInfo" class="file-detail">
      <!-- 文件预览 -->
      <view class="file-preview">
        <view v-if="isImage" class="image-preview">
          <image 
            :src="fileInfo.fileUrl" 
            mode="aspectFit"
            @tap="previewImage"
            class="preview-image"
          />
        </view>
        
        <view v-else class="document-preview">
          <view class="file-icon-large">
            <u-icon :name="getFileIcon(fileInfo.fileType)" size="60" color="#4a6bef"></u-icon>
          </view>
          <text class="file-name">{{ fileInfo.originalName }}</text>
          <text v-if="fileInfo.pageCount" class="page-count">共 {{ fileInfo.pageCount }} 页</text>
        </view>
      </view>
      
      <!-- 文件基本信息 -->
      <view class="file-info-section">
        <view class="section-title">
          <view class="title-bar"></view>
          <text>基本信息</text>
        </view>
        
        <view class="info-list">
          <view class="info-item">
            <text class="info-label">文件名</text>
            <text class="info-value">{{ fileInfo.originalName }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">文件大小</text>
            <text class="info-value">{{ formatFileSize(fileInfo.fileSize) }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">文件类型</text>
            <text class="info-value">{{ getFileTypeName(fileInfo.fileType) }}</text>
          </view>
          
          <view v-if="fileInfo.pageCount" class="info-item">
            <text class="info-label">页数</text>
            <text class="info-value">{{ fileInfo.pageCount }} 页</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">上传时间</text>
            <text class="info-value">{{ formatDateTime(fileInfo.createdAt) }}</text>
          </view>
          
          <view class="info-item">
            <text class="info-label">最后修改</text>
            <text class="info-value">{{ formatDateTime(fileInfo.updatedAt) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <view class="action-row">
          <button 
            class="action-btn primary"
            @click="printFile"
          >
            <u-icon name="printer" size="20" color="#ffffff" class="btn-icon"></u-icon>
            <text>打印文件</text>
          </button>
          
          <button 
            class="action-btn secondary"
            @click="previewFile"
          >
            <u-icon name="eye" size="20" color="#ffffff" class="btn-icon"></u-icon>
            <text>预览文件</text>
          </button>
        </view>
        
        <button 
          class="action-btn outline"
          @click="downloadFile"
        >
          <u-icon name="download" size="20" color="#4a6bef" class="btn-icon"></u-icon>
          <text>下载文件</text>
        </button>
      </view>
      
      <!-- 打印历史 -->
      <view v-if="printHistory.length > 0" class="print-history-section">
        <view class="section-title">
          <view class="title-bar"></view>
          <text>打印历史</text>
        </view>
        
        <view class="history-list">
          <view 
            v-for="record in printHistory" 
            :key="record.id"
            class="history-item"
          >
            <view class="history-info">
              <text class="history-title">{{ record.printOptions.paperSize }} {{ record.printOptions.colorType === 'color' ? '彩色' : '黑白' }}打印</text>
              <text class="history-meta">{{ record.quantity }}份 · {{ formatDateTime(record.createdAt) }}</text>
            </view>
            <view class="history-status">
              <u-tag 
                :text="getStatusText(record.status)" 
                :type="getStatusType(record.status)"
                size="mini"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <u-empty 
        mode="data"
        icon="http://cdn.uviewui.com/uview/empty/data.png"
        text="文件不存在或已被删除"
        textColor="#909399"
      >
        <template #bottom>
          <button 
            class="error-btn"
            @click="goBack"
          >
            返回文件列表
          </button>
        </template>
      </u-empty>
    </view>
    
    <!-- 操作菜单 -->
    <u-action-sheet 
      :show="showActions" 
      :actions="actionList"
      @close="showActions = false"
      @select="handleAction"
      title="文件操作"
      :round="10"
      :cancelText="'取消'"
    />
    
    <!-- 删除确认弹窗 -->
    <u-modal 
      :show="showDeleteModal"
      title="删除确认"
      content="确定要删除这个文件吗？删除后无法恢复，相关的打印记录也会受到影响。"
      @confirm="confirmDelete"
      @cancel="showDeleteModal = false"
      confirmColor="#f56c6c"
      showCancelButton
    />
  </view>
</template>

<script>
export default {
  name: 'FileDetail',
  data() {
    return {
      fileId: null,
      fileInfo: null,
      printHistory: [],
      loading: true,
      showActions: false,
      showDeleteModal: false,
      actionList: [
        { name: '预览文件', value: 'preview', icon: 'eye', iconColor: '#4a6bef' },
        { name: '下载文件', value: 'download', icon: 'download', iconColor: '#19be6b' },
        { name: '打印文件', value: 'print', icon: 'printer', iconColor: '#4a6bef' },
        { name: '删除文件', value: 'delete', icon: 'trash', iconColor: '#f56c6c' }
      ]
    }
  },
  
  computed: {
    // 是否为图片文件
    isImage() {
      return this.fileInfo && this.fileInfo.fileType && this.fileInfo.fileType.startsWith('image/')
    }
  },
  
  onLoad(options) {
    this.fileId = parseInt(options.id)
    if (this.fileId) {
      this.loadFileDetail()
      this.loadPrintHistory()
    } else {
      this.loading = false
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载文件详情
    async loadFileDetail() {
      this.loading = true
      
      try {
        const response = await this.$http.get(`/api/files/${this.fileId}`)
        
        if (response.data.success) {
          this.fileInfo = response.data.data
        } else {
          throw new Error(response.data.message)
        }
      } catch (error) {
        console.error('加载文件详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        this.fileInfo = null
      } finally {
        this.loading = false
      }
    },
    
    // 加载打印历史
    async loadPrintHistory() {
      try {
        const response = await this.$http.get(`/api/files/${this.fileId}/print-history`)
        
        if (response.data.success) {
          this.printHistory = response.data.data || []
        } else {
          this.printHistory = []
        }
      } catch (error) {
        console.error('加载打印历史失败:', error)
        this.printHistory = []
      }
    },
    
    // 预览图片
    previewImage() {
      if (this.isImage) {
        uni.previewImage({
          urls: [this.fileInfo.fileUrl],
          current: this.fileInfo.fileUrl
        })
      }
    },
    
    // 预览文件
    previewFile() {
      if (!this.fileInfo) return
      
      uni.navigateTo({
        url: `/pages/files/preview?id=${this.fileInfo.id}`
      })
    },
    
    // 打印文件
    printFile() {
      if (!this.fileInfo) return
      
      uni.navigateTo({
        url: `/pages/print/setup?fileId=${this.fileInfo.id}`
      })
    },
    
    // 下载文件
    async downloadFile() {
      if (!this.fileInfo) return
      
      try {
        uni.showLoading({ 
          title: '准备下载...',
          mask: true
        })
        
        const response = await this.$http.get(`/api/files/${this.fileInfo.id}/download`)
        
        if (response.data.success) {
          const downloadUrl = response.data.data.downloadUrl
          
          // 在小程序中下载文件
          uni.downloadFile({
            url: downloadUrl,
            success: (res) => {
              if (res.statusCode === 200) {
                uni.hideLoading()
                uni.saveFile({
                  tempFilePath: res.tempFilePath,
                  success: () => {
                    uni.showToast({
                      title: '下载成功',
                      icon: 'success'
                    })
                  },
                  fail: (err) => {
                    console.error('保存文件失败:', err)
                    uni.showToast({
                      title: '保存失败',
                      icon: 'none'
                    })
                  }
                })
              }
            },
            fail: (err) => {
              console.error('下载文件失败:', err)
              uni.showToast({
                title: '下载失败',
                icon: 'none'
              })
            },
            complete: () => {
              uni.hideLoading()
            }
          })
        } else {
          throw new Error(response.data.message || '下载失败')
        }
      } catch (error) {
        console.error('下载文件失败:', error)
        uni.showToast({
          title: error.message || '下载失败',
          icon: 'none'
        })
        uni.hideLoading()
      }
    },
    
    // 处理操作菜单
    handleAction(action) {
      this.showActions = false
      
      switch (action.value) {
        case 'preview':
          this.previewFile()
          break
        case 'download':
          this.downloadFile()
          break
        case 'print':
          this.printFile()
          break
        case 'delete':
          this.showDeleteModal = true
          break
      }
    },
    
    // 确认删除文件
    async confirmDelete() {
      this.showDeleteModal = false
      
      try {
        uni.showLoading({ 
          title: '删除中...',
          mask: true
        })
        
        const response = await this.$http.delete(`/api/files/${this.fileInfo.id}`)
        
        if (response.data.success) {
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(response.data.message || '删除失败')
        }
      } catch (error) {
        console.error('删除文件失败:', error)
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 获取文件类型名称
    getFileTypeName(fileType) {
      const typeMap = {
        'application/pdf': 'PDF文档',
        'application/msword': 'Word文档',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word文档',
        'application/vnd.ms-excel': 'Excel表格',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel表格',
        'application/vnd.ms-powerpoint': 'PowerPoint演示文稿',
        'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'PowerPoint演示文稿',
        'text/plain': '文本文档',
        'image/jpeg': 'JPEG图片',
        'image/png': 'PNG图片',
        'image/gif': 'GIF图片',
        'image/bmp': 'BMP图片'
      }
      
      return typeMap[fileType] || '未知类型'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    },
    
    // 获取状态类型
    getStatusType(status) {
      const typeMap = {
        'pending': 'warning',
        'processing': 'primary',
        'completed': 'success',
        'cancelled': 'error'
      }
      return typeMap[status] || 'info'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      if (!dateString) return '未知时间'
      
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.file-detail-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 40rpx;
}

.navbar-right {
  padding: 0 20rpx;
}

.loading-container, .error-container {
  padding: 120rpx 40rpx;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #909399;
  }
}

.error-btn {
  margin-top: 30rpx;
  background: #4a6bef;
  color: white;
  font-size: 28rpx;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  border: none;
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}

.file-preview {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 40rpx;
  text-align: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.image-preview {
  .preview-image {
    width: 100%;
    max-height: 400rpx;
    border-radius: 12rpx;
  }
}

.document-preview {
  .file-icon-large {
    margin-bottom: 20rpx;
  }
  
  .file-name {
    display: block;
    font-size: 32rpx;
    color: #303133;
    font-weight: 500;
    margin-bottom: 12rpx;
  }
  
  .page-count {
    font-size: 28rpx;
    color: #909399;
  }
}

.file-info-section, .print-history-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30rpx;
  
  .title-bar {
    width: 6rpx;
    height: 32rpx;
    background: #4a6bef;
    border-radius: 3rpx;
    margin-right: 16rpx;
  }
}

.info-list {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .info-label {
      font-size: 30rpx;
      color: #606266;
    }
    
    .info-value {
      font-size: 30rpx;
      color: #303133;
      text-align: right;
      flex: 1;
      margin-left: 40rpx;
      word-break: break-all;
    }
  }
}

.action-buttons {
  margin: 20rpx;
  
  .action-row {
    display: flex;
    gap: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    border-radius: 44rpx;
    font-size: 30rpx;
    border: none;
    
    .btn-icon {
      margin-right: 8rpx;
    }
    
    &.primary {
      flex: 1;
      background: #4a6bef;
      color: white;
      
      &:active {
        opacity: 0.9;
        transform: scale(0.98);
      }
    }
    
    &.secondary {
      flex: 1;
      background: #19be6b;
      color: white;
      
      &:active {
        opacity: 0.9;
        transform: scale(0.98);
      }
    }
    
    &.outline {
      width: 100%;
      background: white;
      color: #4a6bef;
      border: 1rpx solid #4a6bef;
      
      &:active {
        background: #f0f5ff;
        transform: scale(0.98);
      }
    }
  }
}

.history-list {
  .history-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .history-info {
      flex: 1;
      
      .history-title {
        display: block;
        font-size: 30rpx;
        color: #303133;
        margin-bottom: 8rpx;
      }
      
      .history-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
    
    .history-status {
      margin-left: 20rpx;
    }
  }
}
</style>